using AutoMapper;
using UwinEducation.Application.Common.Interfaces;
using UwinEducation.Application.Dtos;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Shared.Models;

namespace UwinEducation.Application.Services
{
    public class TermService : ITermService
    {
        private readonly ITermRepository _termRepository;
        private readonly IMapper _mapper;

        public TermService(ITermRepository termRepository, IMapper mapper)
        {
            _termRepository = termRepository;
            _mapper = mapper;
        }

        public async Task<PagedResult<TermDto>> GetPagedListAsync(TermPageRequest pageRequest)
        {
            var result = await _termRepository.GetPagedListAsync(pageRequest);
            return new PagedResult<TermDto>
            {
                Total = result.Total,
                Items = _mapper.Map<List<TermDto>>(result.Items)
            };
        }

        public async Task<TermDto> GetByIdAsync(Guid id)
        {
            var term = await _termRepository.GetDetailsByIdAsync(id);
            if (term == null)
            {
                throw new ArgumentException($"学期不存在: {id}");
            }

            return _mapper.Map<TermDto>(term);
        }

        public async Task<TermDto> CreateAsync(CreateTermDto input)
        {
            if (await _termRepository.ExistsByNameAsync(input.Name))
            {
                throw new ArgumentException($"学期名称已存在: {input.Name}");
            }

            var term = Term.Create(
                input.Name,
                input.ShortName,
                input.StartTime,
                input.EndTime,
                input.Remarks ?? string.Empty
            );

            await _termRepository.AddAsync(term);
            return await GetByIdAsync(term.Id);
        }

        public async Task<TermDto> UpdateAsync(UpdateTermDto input)
        {
            var term = await _termRepository.GetByIdAsync(input.Id);
            if (term == null)
            {
                throw new ArgumentException($"学期不存在: {input.Id}");
            }

            if (await _termRepository.ExistsByNameAsync(input.Name, input.Id))
            {
                throw new ArgumentException($"学期名称已存在: {input.Name}");
            }

            term.Name = input.Name;
            term.ShortName = input.ShortName;
            term.StartTime = input.StartTime;
            term.EndTime = input.EndTime;
            term.Remarks = input.Remarks ?? term.Remarks;

            await _termRepository.UpdateAsync(term);
            return await GetByIdAsync(term.Id);
        }

        public async Task DeleteAsync(Guid id)
        {
            var term = await _termRepository.GetByIdAsync(id);
            if (term == null)
            {
                throw new ArgumentException($"学期不存在: {id}");
            }

            await _termRepository.DeleteAsync(id);
        }
    }
} 